﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using InTheHand.Net.Sockets;

namespace SensorDrone.Net
{
    public class SensorDroneProvider : ISensorDroneProvider
    {
        private readonly BluetoothClient         _client;
        private CancellationTokenSource         _token;
        
        
        public SensorDroneProvider()
        {
            _client = new BluetoothClient();
            _token = new  CancellationTokenSource();
        }

        public Task<IEnumerable<ISensorDrone>> ScanAsync()
        {
            _token.Cancel();
            _token = new CancellationTokenSource();
            var task = Task<IEnumerable<ISensorDrone>>.Factory.StartNew(Find, _token.Token);
            return task;
        }

        public void Stop()
        {
            _token.Cancel();
        }

        private IEnumerable<SensorDrone> Find()
        {
            var drones = new List<SensorDrone>();
            var devices = _client.DiscoverDevices();
            drones.AddRange(devices.Where(device=>device.DeviceName.Contains("Sensordrone")).Select(device=>new SensorDrone(device,new CancellationTokenSource())));

            return drones;
        }
    }
}
